package game;

import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener ;
import java.awt.event.MouseEvent ;
import java.awt.event.InputEvent ;
import java.awt.image.MemoryImageSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.Timer;

public class Rev_Ulti extends Game {
    /*P1 is virtual player. The player that plays is P2*/
    double money_won = 0.0 ;
    /** Intial money given to virtual P1. */
    double p1_init_money =0.0;
    double increment;
    double p1_money_passed = 0.0 ;
    String stage = "0" ;
    int totalTime=60,secs = totalTime, timeTaken=0, thinkTimeTaken=0, thinkSecs=0;
    Timer time = new Timer(1000, new TimeListener());
    Timer thinkTime = new Timer(1000, new ThinkTimeListener());

	// Game log constants.
	final int GL_P2_ACCEPT = 1;
	final int GL_P2_REJECT = 0;

    /** Creates new form Rev_Ulti */
    public Rev_Ulti() {
        super();
//        super("",
//              false, //resizable
//              false, //closable
//              false, //maximizable
//              false);//iconifiable
//        javax.swing.plaf.InternalFrameUI ui = this.getUI();
//        ((javax.swing.plaf.basic.BasicInternalFrameUI)ui).setNorthPane(null);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        p1_init_money = 4.0;
        increment = 0.25;
        initComponents();
        this.setVisible(true);
        calculateResult() ;
        setLocation(screenSize.width/2-400, screenSize.height/2-300);
        addMouseListener( new Rev_Ulti.CheckMouse() ) ;
        lblLeft.setIcon(new ImageIcon(this.getClass().getResource("/images/redReject.png")));
        lblRight.setIcon(new ImageIcon(this.getClass().getResource("/images/greenAccept.png")));
        lblLeft.setVisible(false);
        lblRight.setVisible(false);
        
        int min = secs/60;
        int sec = secs%60;
        lblTime.setText(min+":"+((sec<10)?"0":"")+sec);

        Random rand = new Random();
        thinkSecs = rand.nextInt(3) + 5;
        thinkTime.start();

        hideMouse();
    }

        public Rev_Ulti (String params, int currentRep) {
            super();
//            super("",
//              false, //resizable
//              false, //closable
//              false, //maximizable
//              false);//iconifiable
//        javax.swing.plaf.InternalFrameUI ui = this.getUI();
//        ((javax.swing.plaf.basic.BasicInternalFrameUI)ui).setNorthPane(null);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

		String paramPart[] = params.split (",");
        p1_init_money = Double.parseDouble (paramPart[2]);
        increment = Double.parseDouble (paramPart[3]);
		this.params = params;
		repTot = Integer.parseInt (paramPart[1]);
		repNum = currentRep;
		
        initComponents();
        this.setVisible(true);
        setLocation(screenSize.width/2-400, screenSize.height/2-300);

        runner.addMouseListener( new Rev_Ulti.CheckMouse() ) ;
        addMouseListener( new Rev_Ulti.CheckMouse() ) ;
		this.getGlassPane().addMouseListener(new Rev_Ulti.CheckMouse());

        lblLeft.setIcon(new ImageIcon(this.getClass().getResource("/images/redReject.png")));
        lblRight.setIcon(new ImageIcon(this.getClass().getResource("/images/greenAccept.png")));
        lblLeft.setVisible(false);
        lblRight.setVisible(false);
        
        int min = secs/60;
        int sec = secs%60;
        lblTime.setText(min+":"+((sec<10)?"0":"")+sec);

        Random rand = new Random();
        thinkSecs = rand.nextInt(27) + 3;
        thinkTimeTaken = thinkSecs;
        thinkTime.start();

        hideMouse();
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        l4 = new javax.swing.JLabel();
        l2 = new javax.swing.JLabel();
        l3 = new javax.swing.JLabel();
        lblLeft = new javax.swing.JLabel();
        lblRight = new javax.swing.JLabel();
        lblTime = new javax.swing.JLabel();
        lblPlayer = new javax.swing.JLabel();

        setBackground(new java.awt.Color(255, 255, 255));
        setBorder(null);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        l4.setFont(new java.awt.Font("Calibri", 1, 28));
        l4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        l4.setText("Waiting for first player to give some money ...");

        l2.setFont(new java.awt.Font("Calibri", 1, 28));
        l2.setForeground(new java.awt.Color(0, 51, 204));
        l2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);

        l3.setFont(new java.awt.Font("Calibri", 1, 28));
        l3.setForeground(new java.awt.Color(51, 102, 255));

        lblLeft.setFont(new java.awt.Font("Trebuchet MS", 1, 24));
        lblLeft.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/redNext.png"))); // NOI18N

        lblRight.setFont(new java.awt.Font("Trebuchet MS", 1, 24));
        lblRight.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/greenGive.png"))); // NOI18N

        lblTime.setFont(new java.awt.Font("Calibri", 1, 36));
        lblTime.setForeground(new java.awt.Color(153, 102, 0));
        lblTime.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/hrGlass.png"))); // NOI18N
        lblTime.setText("3:00");

        lblPlayer.setFont(new java.awt.Font("Calibri", 1, 28));
        lblPlayer.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblPlayer.setText("You are Player 2");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(lblTime, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(164, 164, 164)
                        .add(l2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 315, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(l3))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(90, 90, 90)
                        .add(lblLeft)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 124, Short.MAX_VALUE)
                        .add(lblRight)
                        .add(100, 100, 100))
                    .add(l4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                    .add(lblPlayer, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(lblTime, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 48, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(lblPlayer, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 48, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(69, 69, 69)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(l3)
                    .add(l2))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 66, Short.MAX_VALUE)
                .add(l4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 128, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(58, 58, 58)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(lblRight)
                    .add(lblLeft))
                .add(67, 67, 67))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

        @Override
    public synchronized void addMouseListener(MouseListener l) {
        super.addMouseListener(l);
    }

    class CheckMouse implements MouseListener{
        public void mousePressed(MouseEvent e) { hideMouse(); }
        public void mouseReleased(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}
        public void mouseClicked(MouseEvent e) {

            int modifiers = e.getModifiers();

            if ((modifiers & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) {
                if( stage.equals("2") ){}
                if( stage.equals("1") ){
                    money_won = p1_money_passed;
                    timeTaken = totalTime - secs ;

					writeLog (playerId + ",2,\"" + params + "\"," + repNum
						+ "," + repTot + ","
						+ String.format ("$%.2f", money_won) + ","
						+ String.format ("$%.2f",
							p1_init_money - p1_money_passed));
					writeGameLog (playerId + ",2," + timeTaken + ","
						+ String.format ("$%.2f", p1_money_passed) + ","
						+ GL_P2_ACCEPT);
					
                    totalMoneyWon += money_won ;
                    System.out.println("G.totalMoneyWon = " + totalMoneyWon) ;
                    l4.setText("You accepted the amount." );
                    l2.setText("");
                    lblRight.setVisible(false);
                    lblLeft.setVisible(false);
                    l3.setText("");
                    stage = "2" ;
                    secs=0;
                }
            }

            if ((modifiers & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK) {}
            if ((modifiers & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
                if( stage.equals("1") ){
                    money_won = 0.0;
                    l4.setText("You rejected the amount." );
                    l2.setText("");
                    timeTaken = totalTime - secs ;
					
                    writeLog (playerId + ",2,\"" + params + "\"," + repNum
						+ "," + repTot + ","
						+ String.format ("$%.2f", money_won) + ",$0.00");
					writeGameLog (playerId + ",2," + timeTaken + ",$0.00,"
						+ GL_P2_REJECT);
					
                    totalMoneyWon += money_won ;
                    System.out.println("G.totalMoneyWon = " + totalMoneyWon) ;
                    lblRight.setVisible(false);
                    lblLeft.setVisible(false);
                    l3.setText("");
                    stage = "2" ;
                    secs=0;
                }
                else if(stage.equals("2")) {}
            }
        }
    }

    public void calculateResult(){
        String line ;
        Random r = new Random();
        double probability = 0, cumm_prob =0 ;
        probability = r.nextDouble();
        System.out.println("probability: " + probability);
        try {
            BufferedReader bin = readGameData() ;
            line = bin.readLine() ;
            line = bin.readLine() ;
            while( line != null ) {
                String str[] = line.split(",") ;
                cumm_prob += Double.parseDouble(str[0]) ;
                System.out.println("Cummalative : " + cumm_prob);
                if( probability > cumm_prob ){
                    line = bin.readLine() ;
                    continue ;
                }
                else{
                    System.out.println("Match: " + str[0] + " " + str[1]);
                    p1_money_passed = Double.parseDouble(str[1]) ;
                    System.out.println("p1_money_passed " + p1_money_passed);
                    break ;
                }
            }
        }
        catch( IOException e ){
             e.printStackTrace();
             logError(e);
        }
    }

    private void hideMouse() {
        int[] pixels = new int[16 * 16];
        Image image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(16, 16, pixels, 0, 16));
        Cursor transparentCursor = Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "invisibleCursor");
        this.getGlassPane().setCursor(transparentCursor);
		this.getGlassPane().setVisible(true);
        runner.setCursor(transparentCursor);
    }

    class TimeListener implements ActionListener {
    	public void actionPerformed(ActionEvent e) {
    		secs--;
            if(secs>=0) {
                int min = secs/60;
                int sec = secs%60;
                lblTime.setText(min+":"+((sec<10)?"0":"")+sec);
            }
            if(secs==0) {
                //time.stop();
                lblLeft.setVisible(false);
                lblRight.setVisible(false);
                stage="5";
                l2.setText(null);
                l3.setText(null);
                l4.setText("Sorry, your time is up.");
                writeLog (playerId + ",2,\"" + params + "\"," + repNum
					+ "," + repTot + ",TimeOut,TimeOut");
				writeGameLog (playerId + ",1," + timeTaken
					+ ",TimeOut,TimeOut");
                totalMoneyWon += 0.0 ;
                System.out.println("G.totalMoneyWon = " + totalMoneyWon) ;

            }
            if(secs==-6) {
                time.stop();
                try {
                    setVisible(false);
                    free=true;
                } catch(Exception ex) {
                    ex.printStackTrace();
                    logError(ex);
                }
            }
    	}

    }

    class ThinkTimeListener implements ActionListener {
    	public void actionPerformed(ActionEvent e) {
    		thinkSecs--;
            if(thinkSecs==0) {
                thinkTime.stop();

                l2.setText("Player 1 gave you");
                l3.setText(String.format ("$%.2f", p1_money_passed));
                l4.setText("What do you want to do ?");
                lblLeft.setVisible(true);
                lblRight.setVisible(true);

                time.start();
                stage = "1" ;
            }
    	}
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JFrame main = new JFrame();
                    JDesktopPane dPane = new JDesktopPane();
                    Rev_Ulti frame = new Rev_Ulti();
                    main.setSize(820, 620);
                    dPane.add(frame);
                    main.add(dPane);
                    main.setVisible(true);
                    dPane.setVisible(true);
                    frame.setSelected(true);
                    frame.setVisible(true);
                } catch(Exception ex) {
                    ex.printStackTrace();
                };
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel l2;
    private javax.swing.JLabel l3;
    private javax.swing.JLabel l4;
    private javax.swing.JLabel lblLeft;
    private javax.swing.JLabel lblPlayer;
    private javax.swing.JLabel lblRight;
    private javax.swing.JLabel lblTime;
    // End of variables declaration//GEN-END:variables

}
